//引入express
const express = require('express');
//创建应用对象
const app = express();
//配置静态资源
app.use(express.static('public'));

//注册路由(get请求)
app.get('/index', (req, res) => {
    //获取请求报文相关的基本数据
    console.log(req.method);// GET
    console.log(req.url);// /index?a=1&b=2
    console.log(req.httpVersion);// 1.1
    console.log(req.headers['host']);// localhost:8989

    console.log(req.path);// /index
    console.log(req.get('host'));// localhost:8989

    //query参数  //req.query包含各个query参数的对象
    const { a, b } = req.query;
    console.log('query参数', a, b);// query参数 1 2
    res.send('get 返回数据');
})

const allUsers = [
    {id: 1, name: 'tom', age: 12},
    {id: 2, name: 'tom2', age: 13},
    {id: 3, name: 'tom3', age: 14},
]
  
app.get('/user/:id', (req, res) => {
    //得到params参数
    const { id } = req.params;
    //查找对应的user返回
    const user = allUsers.find(user => user.id === +id);
    //返回     JSON 数据
    res.send(user);// {"id": 2, "name": "tom2", "age": 13}
})

//注册路由(post请求)
app.post('/index', (req, res) => {
    console.log('处理 /index post请求');

    //body参数
    console.log('body参数', req.body);// 需要使用到后面一个中间件来处理才可用
    
    res.send('post 返回数据')
})

app.listen("8989", () => {
    console.log("服务器启动: http://localhost:8989");
})